package fi.antti.jakisselo {

    import javax.servlet.http.{HttpServlet, HttpServletRequest => HSReq, HttpServletResponse => HSResp}

	class JakisServlet extends HttpServlet
	{
      val data="data"
	  val id="id"
	  val liiga="liiga"
	
      import com.google.appengine.api.datastore.{DatastoreService,DatastoreServiceFactory,Entity,KeyFactory,Key} 
      def dataStore:DatastoreService = DatastoreServiceFactory.getDatastoreService()

      def key(id:String) = KeyFactory.createKey(liiga,id)
      
      class Data (val id:String, val value:String) {
	         def this(id:String, e:Entity)=this(id,e.getProperty(data).toString)
	         def entity = {val e = new Entity(liiga, id); e.setProperty(data, value); e}			 
             override def toString = entity.getProperty(data).toString()
      }
      object Data {
          def apply(id:String, data:String) = new Data(id, data)
		  def apply(id:String, entity:Entity) = new Data(id, entity)
      }
      
	  class Parser (val req:HSReq){
		  def ->(attr:String) = req.getParameter(attr)
	  }
	  object Parser{
	      def apply(req:HSReq) = new Parser(req)
	  }

	  class Dao{
	  }
	  object Dao{
	      def apply() = new Dao()
          def store(id:String,data:String) = dataStore.put(Data(id,data).entity) 
		  def load(id:String) = Data(id,dataStore.get(key(id)))
	  }
	  
	  override def doGet(req : HSReq, resp : HSResp) = {
	      def print(data:Data) = resp.getWriter().print(data.toString)
	      print( Dao.load( Parser(req)->id ) )
	  }

	  override def doPost(req : HSReq, resp : HSResp) = {
	      Dao.store( Parser(req)->id, Parser(req)->data )
	  }
	  	  
	}
}